import { Util } from '@zd/zds-wechat-lib';
const util = {
  ...Util,

  /**
   * 点击事件转发（接受点击事件转发到对应的dom上去）
   * @params {DOM} html dom节点
   */
  dispatchClickEvent: domNode => {
    if (document.all) {
      //IE浏览器
      domNode.click();
    } else {
      //其他浏览器
      var e = document.createEvent('MouseEvents');
      e.initEvent('click', true, true);
      domNode.dispatchEvent(e);
    }
  },

  randomString: len => {
    len = len || 32;
    let $chars =
      'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    let maxPos = $chars.length;
    let pwd = '';
    for (let i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  },

  // 生成随机数
  randomStr: len => {
    let $chars = '1234567890';
    let maxPos = $chars.length;
    let pwd = '';
    for (let i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  },

  urlSearch() {
    let name, value;
    let str = location.href;
    console.log(str);
    let num = str.indexOf('?');
    str = str.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]
    let arr = str.split('&'); //各个参数放到数组里
    let obj = {};
    for (var i = 0; i < arr.length; i++) {
      num = arr[i].indexOf('=');
      if (num > 0) {
        name = arr[i].substring(0, num);
        value = arr[i].substr(num + 1);
        this[name] = value;
        obj = { [name]: value, ...obj };
        // console.log(num,name,value);
      }
    }

    return obj;
  },

  getQueryVariable(variable = 'userId') {
    //通过传字段需要的返回值
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split('=');
      if (pair[0] == variable) {
        return pair[1];
      }
    }
    return false;
  },

  getApiData: (
    params = { header: {}, body: {} },
    isLoading = true,
    isCatch = false,
    sysErr = null,
  ) => {
    return Api.post(
      process.env.NODE_ENV == 'development'
        ? '/CMS/OAHttpJSONServer'
        : '/CMS/OAHttpJSONServer',
      {
        //return Api.post("/SXPMS/HttpJSONServer" , {
        SYS_HEAD: {
          CONSUMER_ID: 'OA123',
          CONSUMER_SEQ_NO: util.randomConsumerSerilNo(),
          TRAN_DATE: util.formatDateStr(),
          TRAN_TIMESTAMP: util.getCurrentTime(),
          X_SXXD_TOKEN: util.getQueryVariable('token'),
          ...params.header,
        },
        BODY: {
          CHANNEL: 'SXOA.XD',
          CHANNEL_SERIALNO: util.randomString(16),
          ...params.body,
        },
      },
      { isLoading, isCatch, end: sysErr },
    );
  },

  // 随机生成流水号(生成规则：OA + 8位日期 + 8位随机数 + 16位随机数取后两位，共20位)
  randomConsumerSerilNo() {
    // 7位随机数
    let str = util.randomStr(8);
    // 16位随机数
    let str1 = util.randomString(16);
    // 获取当前日期
    let date = util.formatDateStr();
    return 'OA' + date + '' + str + '' + str1.substr(14);
  },

  Api: {
    login: (userName, paw) => {
      Api.common_login.post(
        {
          userName: userName,
          password: paw,
        },
        { toast: false },
        res => {
          //console.log(res);
          //存用户信息
          Store.LocalStorage.set(CacheKey.BILL_USER_KEY, res.data);
        },
      );
    },
    sendSmsVerifyCode: phone => {
      //获取短信验证码
      phone = phone ? phone.replace(/\s+/g, '') : phone;
      Api.sendSmsVerifyCode.post(
        {
          phone: phone,
        },
        res => {
          if (!res.success) {
            const { message } = res;
            Toast.info(message);
          }
        },
      );
    },
    validateSmsVerifyCode: (phone, smsVerifyCode, callback) => {
      //验证短信验证码
      phone = phone ? phone.replace(/\s+/g, '') : phone;
      Api.validateSmsVerifyCode.post(
        {
          phone: phone,
          smsVerifyCode: smsVerifyCode,
        },
        res => {
          if (!res.success) {
            const { message } = res;
            Toast.info(message);
          } else {
            callback(res);
          }
        },
      );
    },
  },
  getHost: () => {
    return location.origin;
  },

  //隐藏手机号中间数字
  toPhone(tel) {
    if (!tel) {
      return '--';
    }
    return tel.substr(0, 3) + '****' + tel.substr(7);
  },

  getUserForApi(cb, refresh) {
    const callback = util.isFunction(cb) ? cb : () => null;
    return util.getUser(refresh).then(user => {
      if (user) {
        if (user.rId < 0) {
          callback();
          return Promise.reject();
        } else if (global.__isAuth__) {
          return Promise.resolve(user);
        } else {
          return Api.get('/backend/party/loginUserAuth').then(res => {
            if (res.data) {
              global.__isAuth__ = true;
              return util.getUser(true);
            } else {
              callback();
              return Promise.reject();
            }
          });
        }
      } else {
        callback();
        return Promise.reject();
      }
    });
  },

  //format bank银行卡号
  formatBank(bankNo = null) {
    return String(bankNo)
      .replace(/\s/g, '')
      .replace(/(.{4})(?=.)/g, '$1-');
  },

  //转日期格式
  formatDate(date) {
    return date.substring(0, 10);
  },

  //转日期格式
  formatDateH(date) {
    return date.substring(0, 16);
  },

  //格式化格林日期
  formatDateGMT(TimeStamp) {
    let date = new Date(TimeStamp);
    return (
      date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
    );
  },

  // 获取当前时间戳
  getCurrentTime() {
    let date = new Date();
    return date.getTime() + '';
  },

  // 获取当前日期(yyyyMMdd)
  formatDateStr() {
    let date = new Date();
    let month = date.getMonth() + 1;
    if (month < 10) {
      month = '0' + month;
    }
    return date.getFullYear() + '' + month + '' + date.getDate();
  },

  getUser(refresh) {
    return new Promise(resolve => {
      console.log('开始getUser');
      if (global.__User__ && !refresh) {
        console.log('拿到__User__');
        global.__UserIsLoading__ = false;
        resolve(global.__User__);
      } else {
        if (!global.__UserIsLoading__) {
          console.log('开始getUserInfo');
          global.__UserIsLoading__ = true;
          Api.get(
            '/common/user/getUserInfo',
            {},
            {
              loading: false,
              toast: false,
            },
          )
            .then(obj => {
              console.log('getUserInfo-then');
              global.__UserIsLoading__ = false;
              global.__User__ = obj.data || {};
              resolve(global.__User__);
            })
            .catch(res => {
              console.log('getUserInfo-catch');
              global.__UserIsLoading__ = false;
              if (process.env.NODE_ENV === 'production') {
                location.replace(
                  location.origin + '/chainFront/index.html#/login',
                );
              }
              resolve(null);
            });
        } else {
          const fn = () => {
            setTimeout(() => {
              if (global.__User__) {
                global.__UserIsLoading__ = false;
                resolve(global.__User__);
              } else {
                fn();
              }
            }, 500);
          };
          fn();
        }
      }
    });
  },
  getParty(refresh) {
    return new Promise(resolve => {
      util.getUser().then(user => {
        if (!user) {
          resolve(null);
        }
        if (global.__Party__ && !refresh) {
          global.__PartyIsLoading__ = false;
          resolve(global.__Party__);
        } else if (user) {
          if (!global.__PartyIsLoading__) {
            global.__PartyIsLoading__ = true;
            Api.get(
              '/backend/party/findById',
              {
                id: user.rId,
              },
              {
                loading: false,
                message: false,
              },
            )
              .then(obj => {
                global.__PartyIsLoading__ = false;
                global.__Party__ = obj.data;
                resolve(global.__Party__);
              })
              .catch(res => {
                global.__PartyIsLoading__ = false;
                resolve(null);
              });
          } else {
            const fn = () => {
              setTimeout(() => {
                if (global.__Party__) {
                  global.__PartyIsLoading__ = false;
                  resolve(global.__Party__);
                } else {
                  fn();
                }
              }, 500);
            };
            fn();
          }
        }
      });
    });
  },
  logout() {
    return Api.get('/common/login/logout').then(() => {
      global.__User__ = null;
      global.__Party__ = null;
      global.__UserIsLoading__ = false;
      global.__PartyIsLoading__ = false;
      Store.clearAll();
      Store.LocalStorage.clearAll();
      Store.Cookie.clearAll();
      return Promise.resolve();
    });
  },
  previewImage(ids = [], currentId) {
    if (!Util.isArray(ids)) {
      ids = [ids];
    }
    ids = ids.map(id => `${location.origin}/obs/viewFilePublic.json?id=${id}`);
    currentId = currentId
      ? `${location.origin}/obs/viewFilePublic.json?id=${currentId}`
      : null;
    if (process.env.NODE_ENV === 'production') {
      wx.previewImage({
        current: currentId ? currentId : ids[0],
        urls: ids,
      });
    } else {
      console.log(`显示：${ids.join(',')}`);
    }
  },
  isAuth() {
    return Enum.ready().then(() => {
      return util.getUser().then(user => {
        return util.getParty().then(res => {
          if (
            res.memberStatusEnum.name === Enum.PartyStatusEnum.AUDIT_PASSED.name
          ) {
            return Promise.resolve();
          } else {
            return Promise.reject();
          }
        });
      });
    });
  },

  getHotLine(refresh) {
    return new Promise(resolve => {
      if (global.__HotLine__ && !refresh) {
        global.__HotLineIsLoading__ = false;
        resolve(global.__HotLine__);
      } else {
        if (!global.__HotLineIsLoading__) {
          global.__HotLineIsLoading__ = true;
          Api.get('/backend/party/findPlatFormHotLine.json', null, {
            loading: false,
            toast: false,
          })
            .then(res => {
              global.__HotLineIsLoading__ = false;
              global.__HotLine__ = res.data;
              resolve(global.__HotLine__);
            })
            .catch(res => {
              global.__HotLineIsLoading__ = false;
              resolve(null);
            });
        } else {
          const fn = () => {
            setTimeout(() => {
              if (global.__HotLine__) {
                global.__HotLineIsLoading__ = false;
                resolve(global.__HotLine__);
              } else {
                fn();
              }
            }, 500);
          };
          fn();
        }
      }
    });
  },
};

export default util;
